package com.wootion.cims.module.basicinformation.communitysetup.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.wootion.cims.dao.*;
import com.wootion.cims.module.basicinformation.communitysetup.service.CommunitySituationService;
import com.wootion.cims.module.basicinformation.plotsetting.model.Building;
import com.wootion.cims.module.basicinformation.plotsetting.model.PlotMessage;
import com.wootion.cims.module.basicinformation.plotsetting.model.Unit;
import com.wootion.cims.module.communitypersonal.model.Person;
import com.wootion.cims.module.communityresidence.residencelist.model.Residence;
import com.wootion.cims.module.systemsetting.community.model.SysCommunity;
import com.wootion.cims.module.systemsetting.polt.model.SysPlot;
import com.wootion.cims.module.systemsetting.role.model.SysMenu;
import com.wootion.cims.module.systemsetting.role.model.SysRole;
import com.wootion.cims.module.systemsetting.user.dto.UserInfoDto;
import com.wootion.cims.module.systemsetting.user.model.SysUserCommunity;
import com.wootion.cims.module.systemsetting.user.model.SysUserRole;
import com.wootion.cims.module.systemsetting.user.model.User;
import com.wootion.cims.response.ResponseResult;
import com.wootion.cims.response.ResultCode;
import com.wootion.cims.shiro.utils.ShiroUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * Created with IntelliJ IDEA.
 *
 * @Author: jack
 * @Date: 2022/12/02/11:14
 * @Description:
 */
@Slf4j
@Service
public class CommunitySituationServiceImpl implements CommunitySituationService {
    
    @Resource
    private UserDao sysUserDao;

    @Resource
    private SysUserRoleDao sysUserRoleDao;

    @Resource
    private SysUserCommunityDao sysUserCommunityDao;

    @Resource
    private SysRoleDao sysRoleDao;

    @Resource
    private SysRoleMenuDao sysRoleMenuDao;

    @Resource
    private SysMenuDao sysMenuDao;

    @Resource
    private SysCommunityDao sysCommunityDao;

    @Resource
    private SysPlotDao sysPlotDao;

    @Override
    public ResponseResult userInfo() {
        UserInfoDto userInfoDto = new UserInfoDto();
        User user = (User) ShiroUtils.getSubject().getPrincipal();
        if(Objects.isNull(user)){
            return ResponseResult.builder().code(ResultCode.SYSTEM_ERROR.getCode()).message(ResultCode.SYSTEM_ERROR.getMessage()).build();
        }else{
            if(!StringUtils.hasText(user.getId())){
                return ResponseResult.builder().code(ResultCode.SYSTEM_ERROR.getCode()).message(ResultCode.SYSTEM_ERROR.getMessage()).build();
            }
        }
        LambdaQueryWrapper<User> userLambdaQueryWrapper = new LambdaQueryWrapper<>();
        userLambdaQueryWrapper.eq(User::getId,user.getId());
        //查询用户信息
        User user1 = sysUserDao.selectOne(userLambdaQueryWrapper);
        //查询出当前用户的角色的id
        LambdaQueryWrapper<SysUserRole> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(SysUserRole::getUserId,user1.getId());
        SysUserRole sysUserRole = sysUserRoleDao.selectOne(wrapper);
        //查询当前用户的角色信息
        if(!Objects.isNull(sysUserRole)){
            LambdaQueryWrapper<SysRole> wrapper1 = new LambdaQueryWrapper<>();
            wrapper1.eq(SysRole::getId,sysUserRole.getRoleId());
            wrapper1.eq(SysRole::getEnabled,true);
            SysRole sysRole = sysRoleDao.selectOne(wrapper1);
            userInfoDto.setSysRole(sysRole);
            if(Objects.isNull(sysRole)){
                //无角色
                userInfoDto.setSysRole(null);
                //有一个默认的基础信息菜单，和下面的社区概况
                LambdaQueryWrapper<SysMenu> lambdaQueryWrapper = new LambdaQueryWrapper<>();
                lambdaQueryWrapper.eq(SysMenu::getValue, "Situation");
                List<SysMenu> defaultMenus = sysMenuDao.selectList(lambdaQueryWrapper);

                LambdaQueryWrapper<SysMenu> lambdaQueryWrapper2 = new LambdaQueryWrapper<>();
                lambdaQueryWrapper2.eq(SysMenu::getValue, "Verify");
                SysMenu sysMenu = sysMenuDao.selectOne(lambdaQueryWrapper2);
                defaultMenus.add(sysMenu);

                userInfoDto.setSysMenus(defaultMenus);
                userInfoDto.setUser(user1);
                return ResponseResult.builder().data(userInfoDto).build();
            }
            //根据用户的角色id，查询菜单id
            List<String> menuIds = sysRoleMenuDao.menuIds(sysRole.getId());
            if(menuIds.size() <= 0){
                return ResponseResult.builder().data(userInfoDto).build();
            }
            List<SysMenu> sysMenus = sysMenuDao.findByIds(menuIds);
            if(user1.getUsername().equals("admin")){
                List<SysMenu> sysMenus1 = sysMenus.stream().filter(p -> !(p.getValue().equals("Verify"))).collect(Collectors.toList());
                userInfoDto.setSysMenus(sysMenus1);
            }else{
                //设置用户信息，角色信息，菜单信息
                userInfoDto.setSysMenus(sysMenus);
            }
        }else{
            //无角色
            userInfoDto.setSysRole(null);
            //有一个默认的基础信息菜单，和下面的社区概况
            LambdaQueryWrapper<SysMenu> lambdaQueryWrapper = new LambdaQueryWrapper<>();
            lambdaQueryWrapper.eq(SysMenu::getValue, "Situation");

            LambdaQueryWrapper<SysMenu> lambdaQueryWrapper2 = new LambdaQueryWrapper<>();
            lambdaQueryWrapper2.eq(SysMenu::getValue, "Verify");
            SysMenu sysMenu = sysMenuDao.selectOne(lambdaQueryWrapper2);

            List<SysMenu> defaultMenus = sysMenuDao.selectList(lambdaQueryWrapper);
            defaultMenus.add(sysMenu);
            userInfoDto.setSysMenus(defaultMenus);
        }
        userInfoDto.setUser(user1);
        return ResponseResult.builder().data(userInfoDto).build();
    }
    @Override
    public ResponseResult findByCommunityAndPolt() {
        User user = (User) ShiroUtils.getSubject().getPrincipal();
        if(Objects.isNull(user)){
            return ResponseResult.builder().code(ResultCode.SYSTEM_ERROR.getCode()).message(ResultCode.SYSTEM_ERROR.getMessage()).build();
        }else{
            if(!StringUtils.hasText(user.getId())){
                return ResponseResult.builder().code(ResultCode.SYSTEM_ERROR.getCode()).message(ResultCode.SYSTEM_ERROR.getMessage()).build();
            }
        }
        //查询出当前用户的角色的id
        LambdaQueryWrapper<SysUserRole> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(SysUserRole::getUserId,user.getId());
        SysUserRole sysUserRole = sysUserRoleDao.selectOne(wrapper);
        if(!Objects.isNull(sysUserRole)){
            //查询当前用户的角色信息
            LambdaQueryWrapper<SysRole> wrapper1 = new LambdaQueryWrapper<>();
            wrapper1.eq(SysRole::getId,sysUserRole.getRoleId());
            wrapper1.eq(SysRole::getEnabled,true);
            SysRole sysRole = sysRoleDao.selectOne(wrapper1);
            if(Objects.isNull(sysRole)){
                //如果不是超级管理员
                LambdaQueryWrapper<SysUserCommunity> wrapper2 = new LambdaQueryWrapper<>();
                wrapper2.eq(SysUserCommunity::getUserId,user.getId());
                //先查询出他管辖的多个社区id
                List<SysUserCommunity> sysUserCommunities = sysUserCommunityDao.selectList(wrapper2);
                if(sysUserCommunities.size() <= 0){
                    return ResponseResult.builder().code(ResultCode.SYSTEM_ERROR.getCode()).message("当前用户暂时没有任何社区权限，请联系管理员！").build();
                }
                //再根据多个社区id查询对应的多个小区信息
                LambdaQueryWrapper<SysCommunity> wrapper3 = new LambdaQueryWrapper<>();
                List<String> communities = new ArrayList<>();
                for (SysUserCommunity sysUserCommunity : sysUserCommunities) {
                    communities.add(sysUserCommunity.getCommunityId());
                }
                wrapper3.in(communities.size()>0,SysCommunity::getId,communities);
                wrapper3.eq(SysCommunity::getEnable,true);
                List<SysCommunity> communities1 = sysCommunityDao.selectList(wrapper3);
                //再查询每一个社区对应的小区信息
                for (SysCommunity community : communities1) {
                    LambdaQueryWrapper<SysPlot> queryWrapper = new LambdaQueryWrapper<>();
                    queryWrapper.eq(SysPlot::getCommunityId,community.getId());
                    queryWrapper.eq(SysPlot::getEnabled,true);
                    List<SysPlot> sysPlotList = sysPlotDao.selectList(queryWrapper);
                    //统计小区的楼栋数，应住户数
                    for (SysPlot sysPlot : sysPlotList) {
                        //实住户数，已经入住的住宅
                        List<Residence> residenceList = sysPlotDao.countOneOccupancy(sysPlot.getId());
                        if(residenceList != null && residenceList.size()>0){
                            sysPlot.setActualOccupancy(residenceList.size());
                        }else{
                            sysPlot.setActualOccupancy(0);
                        }
                        //当前小区下所有房屋数
                        List<Residence> residenceList1 = sysPlotDao.countOnePlot(sysPlot.getId());
                        //空房数，当前小区的空房数 总房数-实际入住数
                        int occupancy = sysPlot.getActualOccupancy();//实际入住数
                        int size = residenceList1.size();
                        int vacantRoom = size - occupancy;
                        sysPlot.setAnyVacancies(vacantRoom);//设置空房数
                        //租户数,先将当前小区中关联的所有住宅id拿到
                        List<String> abodeIds = new ArrayList<>();
                        for (Residence residence : residenceList1) {
                            abodeIds.add(residence.getId());
                        }
                        List<Map<String, Object>> maps = null;
                        if(abodeIds.size()>0){
                            maps = sysPlotDao.countTenantNum(abodeIds);
                        }
                        if(maps != null && maps.size()>0){
                            sysPlot.setTenant(maps.size());
                        }else {
                            sysPlot.setTenant(0);
                        }
                        //统计人口数
                        if(abodeIds.size()>0){
                            List<Person> people = sysPlotDao.countPerson(abodeIds);
                            if(people != null && people.size()>0){
                                sysPlot.setNumberPeople(people.size());
                            }else {
                                sysPlot.setNumberPeople(0);
                            }
                        }else {
                            sysPlot.setNumberPeople(0);
                        }
                        //统计单元数
                        String buildingUnit = sysPlot.getBuildingUnit();
                        if(!StringUtils.hasText(buildingUnit)){//没有单元和楼栋
                            sysPlot.setBuildingCount(0);
                            sysPlot.setNumberUnits(0);
                        }else{
                            PlotMessage plotMessage = JSON.parseObject(buildingUnit, PlotMessage.class);
                            List<Building> buildings = plotMessage.getBuildings();//智力暂时只统计了楼房数量
                            if(buildings != null && buildings.size()>0){
                                //统计楼栋数
                                sysPlot.setBuildingCount(buildings.size());
                                int count = 0;
                                for (Building building : buildings) {
                                    List<Unit> units = building.getUnits();
                                    if(units != null && units.size()>0){
                                        int size1 = units.size();
                                        count += size1;
                                    }else {
                                        count += 0;
                                    }
                                }
                                //统计单元数
                                sysPlot.setNumberUnits(count);//单元数
                            }else{
                                //统计楼栋数
                                sysPlot.setBuildingCount(0);//楼栋为0
                                sysPlot.setNumberUnits(0);//单元为0
                            }
                        }
                    }
                    community.setSysPlotList(sysPlotList);
                }
                return ResponseResult.builder().data(communities1).build();
            }
            //如果当前登陆用户是超级管理员
            if("street:admin".equals(sysRole.getRoleKey())){
                //街道管理员，可查看全部社区
                LambdaQueryWrapper<SysCommunity> queryWrapper2 = new LambdaQueryWrapper<>();
                queryWrapper2.eq(SysCommunity::getEnable,true);
                List<SysCommunity> communities = sysCommunityDao.selectList(queryWrapper2);
                for (SysCommunity community : communities) {
                    LambdaQueryWrapper<SysPlot> queryWrapper = new LambdaQueryWrapper<>();
                    queryWrapper.eq(SysPlot::getCommunityId,community.getId());
                    queryWrapper.eq(SysPlot::getEnabled,true);
                    List<SysPlot> sysPlotList = sysPlotDao.selectList(queryWrapper);
                    //统计小区的楼栋数，应住户数
                    for (SysPlot sysPlot : sysPlotList) {
                        //实住户数，已经入住的住宅
                        List<Residence> residenceList = sysPlotDao.countOneOccupancy(sysPlot.getId());
                        if(residenceList != null && residenceList.size()>0){
                            sysPlot.setActualOccupancy(residenceList.size());
                        }else{
                            sysPlot.setActualOccupancy(0);
                        }
                        //当前小区下所有房屋数
                        List<Residence> residenceList1 = sysPlotDao.countOnePlot(sysPlot.getId());
                        //空房数，当前小区的空房数 总房数-实际入住数
                        int occupancy = sysPlot.getActualOccupancy();//实际入住数
                        int size = residenceList1.size();
                        int vacantRoom = size - occupancy;
                        sysPlot.setAnyVacancies(vacantRoom);//设置空房数
                        //租户数,先将当前小区中关联的所有住宅id拿到
                        List<String> abodeIds = new ArrayList<>();
                        for (Residence residence : residenceList1) {
                            abodeIds.add(residence.getId());
                        }
                        List<Map<String, Object>> maps = null;
                        if(abodeIds.size()>0){
                            maps = sysPlotDao.countTenantNum(abodeIds);
                        }
                        if(maps != null && maps.size()>0){
                            sysPlot.setTenant(maps.size());
                        }else {
                            sysPlot.setTenant(0);
                        }
                        //统计人口数
                        if(abodeIds.size()>0){
                            List<Person> people = sysPlotDao.countPerson(abodeIds);
                            if(people != null && people.size()>0){
                                sysPlot.setNumberPeople(people.size());
                            }else {
                                sysPlot.setNumberPeople(0);
                            }
                        }else {
                            sysPlot.setNumberPeople(0);
                        }

                        //统计单元数
                        String buildingUnit = sysPlot.getBuildingUnit();
                        if(!StringUtils.hasText(buildingUnit)){//没有单元和楼栋
                            sysPlot.setBuildingCount(0);
                            sysPlot.setNumberUnits(0);
                        }else{
                            PlotMessage plotMessage = JSON.parseObject(buildingUnit, PlotMessage.class);
                            List<Building> buildings = plotMessage.getBuildings();//智力暂时只统计了楼房数量
                            if(buildings != null && buildings.size()>0){
                                //统计楼栋数
                                sysPlot.setBuildingCount(buildings.size());
                                int count = 0;
                                for (Building building : buildings) {
                                    List<Unit> units = building.getUnits();
                                    if(units != null && units.size()>0){
                                        int size1 = units.size();
                                        count += size1;
                                    }else {
                                        count += 0;
                                    }
                                }
                                //统计单元数
                                sysPlot.setNumberUnits(count);//单元数
                            }else{
                                //统计楼栋数
                                sysPlot.setBuildingCount(0);//楼栋为0
                                sysPlot.setNumberUnits(0);//单元为0
                            }
                        }
                    }
                    community.setSysPlotList(sysPlotList);
                }
                return ResponseResult.builder().data(communities).build();
            }else{
                //如果不是超级管理员
                LambdaQueryWrapper<SysUserCommunity> wrapper2 = new LambdaQueryWrapper<>();
                wrapper2.eq(SysUserCommunity::getUserId,user.getId());
                //先查询出他管辖的多个社区id
                List<SysUserCommunity> sysUserCommunities = sysUserCommunityDao.selectList(wrapper2);
                if(sysUserCommunities.size() <= 0){
                    return ResponseResult.builder().code(ResultCode.SYSTEM_ERROR.getCode()).message("当前用户暂时没有任何社区权限，请联系管理员！").build();
                }
                //再根据多个社区id查询对应的多个小区信息
                LambdaQueryWrapper<SysCommunity> wrapper3 = new LambdaQueryWrapper<>();
                List<String> communities = new ArrayList<>();
                for (SysUserCommunity sysUserCommunity : sysUserCommunities) {
                    communities.add(sysUserCommunity.getCommunityId());
                }
                wrapper3.in(communities.size()>0,SysCommunity::getId,communities);
                wrapper3.eq(SysCommunity::getEnable,true);
                List<SysCommunity> communities1 = sysCommunityDao.selectList(wrapper3);
                //再查询每一个社区对应的小区信息
                for (SysCommunity community : communities1) {
                    LambdaQueryWrapper<SysPlot> queryWrapper = new LambdaQueryWrapper<>();
                    queryWrapper.eq(SysPlot::getCommunityId,community.getId());
                    queryWrapper.eq(SysPlot::getEnabled,true);
                    List<SysPlot> sysPlotList = sysPlotDao.selectList(queryWrapper);
                    //统计小区的楼栋数，应住户数
                    for (SysPlot sysPlot : sysPlotList) {
                        //实住户数，已经入住的住宅
                        List<Residence> residenceList = sysPlotDao.countOneOccupancy(sysPlot.getId());
                        if(residenceList != null && residenceList.size()>0){
                            sysPlot.setActualOccupancy(residenceList.size());
                        }else{
                            sysPlot.setActualOccupancy(0);
                        }
                        //当前小区下所有房屋数
                        List<Residence> residenceList1 = sysPlotDao.countOnePlot(sysPlot.getId());
                        //空房数，当前小区的空房数 总房数-实际入住数
                        int occupancy = sysPlot.getActualOccupancy();//实际入住数
                        int size = residenceList1.size();
                        int vacantRoom = size - occupancy;
                        sysPlot.setAnyVacancies(vacantRoom);//设置空房数
                        //租户数,先将当前小区中关联的所有住宅id拿到
                        List<String> abodeIds = new ArrayList<>();
                        for (Residence residence : residenceList1) {
                            abodeIds.add(residence.getId());
                        }
                        List<Map<String, Object>> maps = null;
                        if(abodeIds.size()>0){
                            maps = sysPlotDao.countTenantNum(abodeIds);
                        }
                        if(maps != null && maps.size()>0){
                            sysPlot.setTenant(maps.size());
                        }else {
                            sysPlot.setTenant(0);
                        }
                        //统计人口数
                        if(abodeIds.size()>0){
                            List<Person> people = sysPlotDao.countPerson(abodeIds);
                            if(people != null && people.size()>0){
                                sysPlot.setNumberPeople(people.size());
                            }else {
                                sysPlot.setNumberPeople(0);
                            }
                        }else {
                            sysPlot.setNumberPeople(0);
                        }
                        //统计单元数
                        String buildingUnit = sysPlot.getBuildingUnit();
                        if(!StringUtils.hasText(buildingUnit)){//没有单元和楼栋
                            sysPlot.setBuildingCount(0);
                            sysPlot.setNumberUnits(0);
                        }else{
                            PlotMessage plotMessage = JSON.parseObject(buildingUnit, PlotMessage.class);
                            List<Building> buildings = plotMessage.getBuildings();//智力暂时只统计了楼房数量
                            if(buildings != null && buildings.size()>0){
                                //统计楼栋数
                                sysPlot.setBuildingCount(buildings.size());
                                int count = 0;
                                for (Building building : buildings) {
                                    List<Unit> units = building.getUnits();
                                    if(units != null && units.size()>0){
                                        int size1 = units.size();
                                        count += size1;
                                    }else {
                                        count += 0;
                                    }
                                }
                                //统计单元数
                                sysPlot.setNumberUnits(count);//单元数
                            }else{
                                //统计楼栋数
                                sysPlot.setBuildingCount(0);//楼栋为0
                                sysPlot.setNumberUnits(0);//单元为0
                            }
                        }
                    }
                    community.setSysPlotList(sysPlotList);
                }
                return ResponseResult.builder().data(communities1).build();
            }
        }

        LambdaQueryWrapper<SysUserCommunity> wrapper2 = new LambdaQueryWrapper<>();
        wrapper2.eq(SysUserCommunity::getUserId,user.getId());
        //先查询出他管辖的多个社区id
        List<SysUserCommunity> sysUserCommunities = sysUserCommunityDao.selectList(wrapper2);
        if(sysUserCommunities.size() <= 0){
            return ResponseResult.builder().code(ResultCode.SYSTEM_ERROR.getCode()).message("当前用户暂时没有任何社区权限，请联系管理员！").build();
        }
        //再根据多个社区id查询对应的多个小区信息
        LambdaQueryWrapper<SysCommunity> wrapper3 = new LambdaQueryWrapper<>();
        List<String> communities = new ArrayList<>();
        for (SysUserCommunity sysUserCommunity : sysUserCommunities) {
            communities.add(sysUserCommunity.getCommunityId());
        }
        wrapper3.in(communities.size()>0,SysCommunity::getId,communities);
        wrapper3.eq(SysCommunity::getEnable,true);
        List<SysCommunity> communities1 = sysCommunityDao.selectList(wrapper3);
        //再查询每一个社区对应的小区信息
        for (SysCommunity community : communities1) {
            LambdaQueryWrapper<SysPlot> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(SysPlot::getCommunityId,community.getId());
            queryWrapper.eq(SysPlot::getEnabled,true);
            List<SysPlot> sysPlotList = sysPlotDao.selectList(queryWrapper);
            community.setSysPlotList(sysPlotList);
        }
        return ResponseResult.builder().data(communities1).build();
        
    }
}
